
package com.swf.seed.security.cert;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.koalii.svs.SvsSign;
import com.koalii.svs.SvsVerify;
import com.swf.seed.base.SdCharset;
import com.swf.seed.util.PropUtil;

/**
 * ClassName: CertSecurityUtil <br/>
 * Function: TODO pfx文件生成签名，cer验证签名. <br/>
 * Reason: TODO ADD REASON(可选). <br/>
 * date: 2014-6-30 上午10:54:22 <br/>
 *
 * @author shenwf10476
 * @version 
 * @since JDK 1.6
 */
public class SecurityCertSigner {
	private static final Logger logger = LoggerFactory
			.getLogger(SecurityCertSigner.class);
	private static final SvsSign signer = new SvsSign();
	//初始化私钥
	static {
		try {
			signer.initSignCertAndKey(PropUtil.getPropValueByCharst("privateKey",SdCharset.UTF_8), PropUtil.getPropValue("privateKeyPwd"));
		} catch (Exception e) {
			logger.error("初始化私钥失败"+e.getMessage(), e);
		}
	}
	
	public static void  initSignCertAndKey(String privateKey,String privateKeyPwd){
		try {
			signer.initSignCertAndKey(privateKey, privateKeyPwd);
		} catch (Exception e) {
			logger.error("初始化私钥失败"+e.getMessage(), e);
		}
	}
	
	/**
	 * 签名字符串,如果给定字符集为null，则使用默认字符集
	 * @param signDataStr  签名字符串
	 * @param charset  签名串字符集
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	public static String signData(String signDataStr,String charset) throws UnsupportedEncodingException, Exception {
		return signer.signData(signDataStr.getBytes(charset!=null?charset:SdCharset.defaultCharset));
	}
	
	
	/**
	 * 签名字节数组
	 * @param bytes  签名字节数组
	 * @return
	 * @throws Exception 
	 */
	public static String  signData(byte[] bytes) throws Exception{
		return signer.signData(bytes);
	}
	
	
	/**
	 * 签名文件
	 * @param fileName 文件名
	 * @return
	 * @throws Exception
	 */
	public static String signFile(String fileName) throws Exception{
		return signer.signFile(fileName);
	}
	
	
	public static boolean  checkSign(byte originData[], String szB64SignedData,
			String szCertFileName){
		int retCode = -1;
		try {
			retCode = SvsVerify.verify(originData,szB64SignedData,szCertFileName);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		if (retCode!=0){
			logger.error("验签失败，错误码："+retCode);
		}
		return retCode==0;
	}
	
	public static void main(String[] args) throws Exception {
		String s =SecurityCertSigner.signData("123".getBytes());
		System.out.println(s);
		System.out.println(SecurityCertSigner.checkSign("123".getBytes(), s,PropUtil.getPropValueByCharst("publicKey",SdCharset.UTF_8) ));
		
	}
}
